package com.fulihui.usercore.sdk.pubsub;

import com.alibaba.fastjson.JSONObject;
import com.fulihui.usercore.sdk.domain.UserLoginRegisterMessage;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.fulihui.usercore.sdk.domain.Constants.REDIS_SUBPUB_LOGGER_NAME;
import static com.fulihui.usercore.sdk.domain.Constants.USER_REGISTER_PUBSUB_CHANNEL;

/**
 * 通过Spring IOC管理此类生成实例，初始化调用init，销毁时调用destroy，然后将自己实现的
 * UserRegisterSubscribeProcessor设置到对象属性中，完成订阅配置。
 * <p>配置样例：</p>
 * <pre>{@code
 * <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
 *     ...
 * </bean>
 *
 * <bean id="userRegisterSubscribeProcessor" class="...实现类"/>
 *
 * <bean id="redisUserRegisterSubscribe" init-method="init" destroy-method="destroy"
 *         class="com.fulihui.usercore.sdk.pubsub.RedisUserLoginRegisterSubscribe">
 *     <property name="jedisPool" ref="jedisPool"/>
 *     <property name="userRegisterSubscribeProcessor" ref="userRegisterSubscribeProcessor"/>
 * </bean>}
 * </pre>
 *
 * @author Willard.Hu on 2017/1/2 0002.
 */
@Setter
public final class RedisUserLoginRegisterSubscribe extends JedisPubSub {
    private static final Logger          log             = LoggerFactory.getLogger(REDIS_SUBPUB_LOGGER_NAME);
    /**
     * 订阅处理
     */
    private final static ExecutorService executorService = Executors.newFixedThreadPool(32);

    /**
     * Redis 连接池
     */
    private JedisPool                           jedisPool;
    /**
     * 用户注册订阅处理器
     */
    private UserLoginRegisterSubscribeProcessor userRegisterSubscribeProcessor;

    private boolean isSubscribe = true;

    public void init() {
        executorService.execute(() -> {
            log.info("初始化用户注册订阅...");
            while (isSubscribe) {
                try (Jedis jedis = jedisPool.getResource()) {
                    jedis.subscribe(this, USER_REGISTER_PUBSUB_CHANNEL);
                } catch (Exception ex) {
                    log.error(ex.getMessage(),ex);
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        });
    }

    public void destroy() {
        log.info("用户注册订阅开始销毁处理...");
        if (!executorService.isShutdown()) {
            executorService.shutdown();
        }
        log.info("用户注册订阅销毁处理成功...");
    }

    @Override
    public void onMessage(String channel, String message) {
        executorService.execute(() -> {
            log.info("收到消息 channel:{}, message:{}", channel, message);
            UserLoginRegisterMessage userRegisterMessage = JSONObject.parseObject(message, UserLoginRegisterMessage.class);
            userRegisterMessage.setChannel(channel);
            userRegisterSubscribeProcessor.process(userRegisterMessage);
        });
    }

    @Override
    public void onPUnsubscribe(String pattern, int subscribedChannels) {
        isSubscribe = false;
    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        isSubscribe = false;
    }
}
